package com.example.dwr.reverseajax;

import java.util.LinkedList;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSessions;

public class JavascriptChat
{
  private final LinkedList<Message> messages;

  public JavascriptChat()
  {
    this.messages = new LinkedList();
  }

  public void addMessage(String text)
  {
    if ((text != null) && (text.trim().length() > 0))
    {
      this.messages.addFirst(new Message(text));
      while (this.messages.size() > 10)
      {
        this.messages.removeLast();
      }
    }

    Browser.withCurrentPage(new Runnable()
    {
      public void run()
      {
        ScriptSessions.addFunctionCall("receiveMessages", new Object[] { messages});
      }
    });
  }
}